package fid

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/labstack/echo"
)

func (f *Fid) getSessionID(paramMap map[string]interface{}) (sid string, err error) {
	sidData, ok := paramMap["sessionid"]
	if !ok {
		sid, err = f.sessionManager.GenerateSessionID()
		if err != nil {
			return "", err
		}
	} else {
		sid, ok = sidData.(string)
		if !ok {
			return "", fmt.Errorf("unkown sessionid")
		} else if len(strings.TrimSpace(sid)) == 0 {
			sid, err = f.sessionManager.GenerateSessionID()
			if err != nil {
				return "", err
			}
		}
	}
	return sid, nil
}

func (f *Fid) getMethod(paramMap map[string]interface{}) (string, error) {
	methodData, ok := paramMap["method"]
	if !ok {
		return "", fmt.Errorf("unkown method")
	}
	method, ok := methodData.(string)
	if !ok {
		return "", fmt.Errorf("unkown method")
	}
	return method, nil
}

func (f *Fid) echoRouter(c echo.Context) error {
	datas := make(map[string]interface{})
	if err := json.NewDecoder(c.Request().Body).Decode(&datas); err != nil {
		return ResponseError(c, ErrBadParam)
	}

	JsonOut(datas)

	sid, err := f.getSessionID(datas)
	if err != nil {
		return ResponseError(c, ErrBadSession)
	}

	sessionStore, err := f.sessionManager.SessionStartWithSessionId(sid)
	if err != nil {
		return ResponseError(c, ErrBadSession)
	}
	defer sessionStore.SessionRelease(c.Response())

	method, err := f.getMethod(datas)
	if err != nil {
		return ResponseError(c, ErrBadRequest)
	}
	for _, pt := range f.protos {
		if strings.HasPrefix(method, pt.Prefix) {
			return pt.Route(c, sessionStore, method, datas)
		}
	}
	return ResponseError(c, ErrBadRequest)
}
